package com.bytezero.login_test;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.bytezero.login_test.BaseActivity.BaseActivity;
import com.bytezero.login_test.home.HomeFragment;
import com.bytezero.login_test.mine.MineFragment;
import com.bytezero.login_test.shop.shopFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.security.acl.Owner;

public class MainActivity extends BaseActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

    private static final String TAG = "MainActivity";
    private Fragment[] fragments;
    private int lastFragmentIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_Login_Test);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        BottomNavigationView bottomNavigationView = findViewById(R.id.main_buttom);
        bottomNavigationView.setOnNavigationItemSelectedListener(this);

        fragments = new Fragment[]{new HomeFragment(), new shopFragment(), new MineFragment()};
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.main_frame, fragments[0])
                .commit();


    }



    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        item.setChecked(true);
        switch (item.getItemId()) {
            case R.id.buttom_home:
                switchFragment(0);
                Log.e(TAG, "onNavigationItemSelected: 首页");
                break;
            case R.id.buttom_shop:
                switchFragment(1);
                Log.e(TAG, "onNavigationItemSelected: 商场");
                break;
            case R.id.buttom_mine:
                switchFragment(2);
                Log.e(TAG, "onNavigationItemSelected: 我的");
                break;
        }
        return false;
    }

    private void switchFragment(int to) {

        if (lastFragmentIndex == to) {
            return;
        }
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (!fragments[to].isAdded()) {
            fragmentTransaction.add(R.id.main_frame, fragments[to]);

        } else {
            fragmentTransaction.show(fragments[to]);
        }
        fragmentTransaction.hide(fragments[lastFragmentIndex]).commitAllowingStateLoss();
        lastFragmentIndex = to;
    }
}